package jsu.blogger.service.impl;

import jsu.blogger.mapper.CommentMapper;
import jsu.blogger.pojo.Comment;
import jsu.blogger.service.inter.CommentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;
@Service
public class CommentServiceImpl implements CommentService {
    private static final Logger log = LoggerFactory.getLogger(CommentServiceImpl.class);
    @Autowired
    private CommentMapper commentMapper;
    @Override
    public List<Comment> getParentComments(Long postId, int begin, int count) {
        return commentMapper.selectParentCommentByPostId(postId,begin,count);
    }
    @Override
    public List<Comment>getSonComments(Long postId, Long parentCommentId, int begin, int count){
        return commentMapper.selectSonCommentByPostIdAndParentCommentId(postId,parentCommentId,begin,count);
    }
    @Override
    @Transactional
    public boolean deleteComment(Long commentId, Long uid){
        //删除之前，先判断他是不是二级评论
        Long parentCommentId=commentMapper.selectIsSonCommentByCommentId(commentId);
        if(parentCommentId==null){
            //是一级评论，所以还要附带删除所有的二级评论
            log.info("用户删除了一级评论，自动删除附属的所有二级评论");
            commentMapper.deleteSonComment(commentId);
            return commentMapper.deleteComment(commentId,uid)==1?true:false;
        }else{
            log.info("删除的是二级评论");
            commentMapper.updateDecreaseParentCommentRepliesCount(parentCommentId);
            return commentMapper.deleteComment(commentId,uid)==1?true:false;
        }
    }
    @Override
    @Transactional
    public int insertComment(Long postId, Long userId, Long parentCommentId, Long replyToUserId, String content, Timestamp createdAt){
        //子评论除了插入，还需要修改父评论
        try {
            if(parentCommentId!=null&&replyToUserId!=null){
                //这是二级评论
                commentMapper.updateIncreaseParentCommentRepliesCount(parentCommentId);
            }
            return commentMapper.insertComment(postId,userId,parentCommentId,replyToUserId,content,createdAt);
        }catch (Exception e){
            log.info(e.getMessage());
            return 0;
        }
    }
    @Override
    public String getParentComment(Long commentId){
     return commentMapper.selectParentCommentByCommentId(commentId);
    }
}
